﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;
using System.Reflection;
using System.Collections.Specialized;

namespace WF.Web.Controls
{
    public class CCHR_FormView : FormView
    {
        public CCHR_FormView()
        {
            this.ItemInserting += new FormViewInsertEventHandler(CCHR_FormView_ItemInserting);
            this.ItemUpdating += new FormViewUpdateEventHandler(CCHR_FormView_ItemUpdating);
        }

        void CCHR_FormView_ItemUpdating(object sender, FormViewUpdateEventArgs e)
        {
            ProcessNullvalue(e.NewValues);
        }

        void CCHR_FormView_ItemInserting(object sender, FormViewInsertEventArgs e)
        {
            ProcessNullvalue(e.Values);
        }

        /// <summary>
        /// 处理空值

        /// 
        /// </summary>
        /// <param name="Values"></param>
        private void ProcessNullvalue(IOrderedDictionary Values)
        {
            if (this.DataSourceObject is System.Web.UI.WebControls.ObjectDataSource)
            {
                string s = ((ObjectDataSource)this.DataSourceObject).DataObjectTypeName;

                //TODO: 修改Hardcode CCHR
                //得到实体对象的类型

                Type dataObjectType = Type.GetType(s + ",CCHR");

                //得到实体对象的所有属性

                PropertyInfo[] Properties = dataObjectType.GetProperties(BindingFlags.Instance | BindingFlags.Public);

                //遍历所有属性

                foreach (PropertyInfo property in Properties)
                {
                    //如果是Nullable
                    if ((property.PropertyType.IsGenericType) && (property.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>)))
                    {
                        //如果界面传回来的是"",则设为null
                        if ((null != Values[property.Name]) && (((string)Values[property.Name]).Trim() == string.Empty))
                        {
                            Values[property.Name] = null;
                        }
                    }
                }
            }
        }
    }
}